<template>
  <div>
    <div class="result-container">
      <div
          class="filter-container"
          :class="isShowFilter && windowWidth > 900 ? '' : 'filter-container__hidden'">
        <course-filter v-model="filterValue" @update="updateFilter"/>
      </div>
      <div class="result-list">
        <div
            class="result-item"
            v-for="item in searchResultList"
            :key="item.id"
            @click="gotoCourseDetail(item.id)">
          <div class="item-image">
            <v-img
                :src="item.pic"
                width="inherit"
                height="inherit"/>
          </div>
          <div class="item-info">
            <div class="item-title">
              {{ item.name }}
            </div>
            <div class="item-desc">
              {{ item.description }}
            </div>
            <div class="item-detail">
              <span class="teacher">
                {{ item.teacherName }}
              </span>
              <span v-if="item.users">
                {{ `${item.users}` }}
              </span>
              <span>
                {{ item.grade | formatGrade }}
              </span>
              <span>
                {{ item.st | formatCourseCategory }}
              </span>
            </div>
          </div>
          <div class="item-price">
            <div class="price__current">
              {{ item.price | formatPrice }}
            </div>
            <div class="price__original" v-if="item.price_old">
              {{ item.price_old | formatPrice }}
            </div>
          </div>
        </div>
      </div>
    </div>
    <v-pagination
        class="my-10"
        v-model="currentPage"
        :length="totalPage"
        circle/>
    <v-navigation-drawer
        class="deep-grey pa-6"
        v-model="isShowAsideFilter"
        temporary
        left
        fixed
        width="260px"
        @close="isShowAsideFilter = false">
      <course-filter v-model="filterValue" @update="updateFilter"/>
    </v-navigation-drawer>
  </div>
</template>

<script>
import {formatCourseCategory} from "@/common/js/utils";
import courseFilter from "@/views/search/searchResult/searchCourses/courseFilter/courseFilter";
import {searchResultList} from "@/views/search/searchResult/searchCourses/mockData";
import {searchCourses} from "@/api";

/**
 * @description 搜索结果组件（课程）
 * @property {String} value 搜索关键词
 * @property {String} showFilter 控制过滤器显示与隐藏
 * @example <searchCourses v-model="..." :showFilter="true"/>
 */
export default {
  name: "searchCourses",
  components: {
    courseFilter
  },
  props: {
    value: {
      type: String,
      default: ""
    },
    showFilter: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      isShowFilter: this.showFilter, //是否显示过滤器
      isShowAsideFilter: false, //是否显示侧边弹出过滤器
      searchResultList: [], //搜索结果列表
      currentPage: 1, //当前页码,
      totalPage: 4, //总页数
      index: 0,
      filterValue: {
        grade: 0,
        priceRange: [0, 500],
      }, //课程筛选器的值
    }
  },
  methods: {
    getSearchResult(sortIndex = null) {
      this.utils.throttle(() => {
        this.searchResultList = searchResultList;
        const sortType = {
          0: '',
          1: 'price',
          2: 'view_count',
          3: 'buy_count'
        }
        let grades = ''
        if (this.filterValue.grade !== 0) {
          grades = '20000' + this.filterValue.grade
        }
        searchCourses(this.currentPage, 10, this.searchValue, grades, this.filterValue.priceRange[0], this.filterValue.priceRange[1], sortType[sortIndex] ?? null).then(res => {
          if (res.success) {
            this.searchResultList = res.data
          }
        }).catch(err => {
          console.error(err);
        });
      }, 500);
    },
    /**
     * 跳转课程详情页
     * @param {String} id 课程ID
     */
    gotoCourseDetail(id) {
      this.$router.push(`/course/${id}`);
    },
    // 课程筛选器触发更新
    updateFilter(filterValue) {
      this.filterValue = filterValue;
      this.getSearchResult(this.index)
    },
  },
  computed: {
    // 屏幕宽度实时数值
    windowWidth() {
      return this.$store.state.screenWidth + 5;
    },
    // 映射props中的showFilter，强制在值变化时触发监听器
    getShowFilter() {
      return this.showFilter;
    },
    // 搜索关键词
    searchValue() {
      return this.value;
    }
  },
  watch: {
    windowWidth(nval, oval) {
      if (nval < oval && nval <= 900) {
        this.isShowFilter = false; //在窗口宽度低于900的时候关闭过滤器
      } else if (nval > oval && nval > 900) {
        this.isShowAsideFilter = false; //在窗口宽度高于900的时候关闭侧边弹出过滤器
        this.isShowFilter = true;
      }
    },
    getShowFilter(nval) {
      this.isShowFilter = nval;
    },
    isShowFilter(nval, oval) {
      if (nval !== oval) {
        this.$emit('switchFilter', nval);
        if (this.windowWidth <= 900) {
          this.isShowAsideFilter = this.isShowFilter;
        }
      }
    },
    isShowAsideFilter(nval, oval) {
      if (nval !== oval) {
        this.$emit('switchFilter', nval);
      }
    },
    searchValue() {
      this.getSearchResult();
    },
    currentPage() {
      this.getSearchResult();
    }
  },
  filters: {
    /**
     * 格式化课程分类
     * @param {String} st 课程小分类ID
     * @return {String} 格式化后的课程分类文字
     */
    formatCourseCategory(st) {
      const category = formatCourseCategory(st);
      return `${category.mt} / ${category.st}`;
    }
  },
  mounted() {

  },
  created() {
    if (this.showFilter) {
      if (this.windowWidth < 900) {
        this.isShowFilter = false;
      }
    }
    this.getSearchResult();
  }
}
</script>

<style lang="scss" scoped>
@import "searchCourses";
</style>